package com.tanhua.server.controller;

import cn.hutool.core.util.RandomUtil;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.model.db.User;

import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

//POST /user/login
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Autowired
    private UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    /*
    * 01 登录---获取验证码
    *
    * 请求方式：POST /login
    * 请求参数： @RequestBody  对象= Map map -->  phone(string)
    * 返回值： ResponseEntity :  null--> 若有 原来需要返回的对象等 则输入对应返回值
    *        ResponseEntity.ok(null);
    *       ResponseEntity.status(500).body(null);
    * */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) throws Exception {

        //int i= 1/0;

        //1、获得传过来的手机号 （确认是否存在） 目前写死该手机号已存在
        String phone = (String) map.get("phone");
        //2, 生成随机的验证码
      //  String code = RandomUtil.randomNumbers(6);

       // smsTemplate.sendSms(phone,code);
        String code="123456";
        //3.存入redis中
        redisTemplate.opsForValue().set("_code"+phone,code,5, TimeUnit.MINUTES);
        //4.构造返回

       //return ResponseEntity.ok(null);
        return  ResponseEntity.ok(null);

    }

    /*
    * 02 登录---验证码校验
    * 请求方式： POST /loginVerification
    * 请求参数: @RequestBody  对象= Map map --> phone	,verificationCode
    * 返回值:                 对象= Map map -->token,  isNew
    *
    * */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
        //
        String phone = (String) map.get("phone");
        String verificationCode=(String)  map.get("verificationCode");

      Map resMap=  userService.loginVerification(phone,verificationCode);

      return ResponseEntity.ok(resMap);

    }



}
